using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Collections;
using Box2D.XNA;

namespace Box2DTest
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;
        Texture2D ball;
        private List<Body> ballBodies;
        private const float scaleFactor = 0.01f;
        private Random r = new Random();

        World myWorld;
        BodyDef theBall;

        public Game1()
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
           myWorld = new World(new Vector2(0,10),true);
           ballBodies = new List<Body>();

            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            ball = Content.Load<Texture2D>("ball");

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
                this.Exit();



            myWorld.Step(1 / 60f, 10, 10);

            HandleClick();

            base.Update(gameTime);

            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.Black);
            spriteBatch.Begin();

            foreach (var ballBody in ballBodies)
            {

                spriteBatch.Draw(ball, ballBody.Position / scaleFactor, null, Color.Orange, ballBody.Rotation,

                                 new Vector2(ball.Width / 2f, ball.Height / 2f), 1, SpriteEffects.None, 0);

            }

            spriteBatch.End();

            base.Draw(gameTime);

           
        }

        private void CreateBall()

      {
          var bodyDef = new BodyDef();

          bodyDef.type = BodyType.Dynamic;

          var ballShape = new CircleShape();

          ballShape._radius = (ball.Width/2f)*scaleFactor;

          var ballFixture = new FixtureDef();

          ballFixture.friction = 0.0f; // no friction

          ballFixture.restitution = 1.0f; // give the ball a perfect bounce

          ballFixture.density = 1.0f;

          ballFixture.shape = ballShape;

 

          var ballBody = myWorld.CreateBody(bodyDef);

          ballBody.CreateFixture(ballFixture);

          ballBody.Position = new Vector2(((float) r.NextDouble()*4.5f + .3f), (float) r.NextDouble()*4.5f + .3f);

          

 

          ballBodies.Add(ballBody);

      }

        private void CreateGroundAndWalls()
        {

            var grounDef = new BodyDef();

            grounDef.type = BodyType.Static;



            var groundFix = new FixtureDef();

            groundFix.restitution = 1.0f;

            groundFix.friction = 0.0f;

            groundFix.density = 0.0f;


            var groundShape = new PolygonShape();



            groundShape.SetAsEdge(new Vector2(0, 8), new Vector2(4.8f, 8.0f));

            var groundBody = myWorld.CreateBody(grounDef);

            groundFix.shape = groundShape;

            groundBody.CreateFixture(groundFix);


            groundShape.SetAsEdge(new Vector2(0, 0), new Vector2(0f, 8.0f));

            var leftBody = myWorld.CreateBody(grounDef);

            groundFix.shape = groundShape;

            leftBody.CreateFixture(groundFix);


            groundShape.SetAsEdge(new Vector2(4.8f, 0), new Vector2(4.8f, 8.0f));

            var rightBody = myWorld.CreateBody(grounDef);

            groundFix.shape = groundShape;

            rightBody.CreateFixture(groundFix);


            groundShape.SetAsEdge(new Vector2(0, 0), new Vector2(4.8f, 0));

            var topBody = myWorld.CreateBody(grounDef);

            groundFix.shape = groundShape;

            topBody.CreateFixture(groundFix);
        }
        private MouseState prevMouseState;

        private void HandleClick()
        {

            var state = Mouse.GetState();



            if (prevMouseState.LeftButton == ButtonState.Released && state.LeftButton == ButtonState.Pressed)
            {

                CreateBall();

            }

            prevMouseState = state;

        }
    }
}
